import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import type { UserInfo } from '@/api/system/types/user'
import { loginByMobile, logoutApi, getUserInfoApi } from '@/api/system/auth'
import { clearToken, getToken, setToken } from '@/utils/auth'
import { getTeamId, clearTeamId, setTeamId } from '@/utils/auth'
import { useRoute, useRouter } from 'vue-router'

const storeSetup = () => {
  const router = useRouter()
  const route = useRoute()
  const userInfo = reactive<Pick<UserInfo, 'realName' | 'avatar'>>({
    realName: '',
    avatar: ''
  })
  const name = computed(() => userInfo.realName)
  const avatar = computed(() => userInfo.avatar)
  const token = ref(getToken() || '')
  const teamId = ref(getTeamId() || '')

  // 重置token
  const resetToken = () => {
    token.value = ''
    teamId.value = ''
    clearToken()
    clearTeamId()
  }

  // 登录
  const login = async (params: { mobile: string; password: string }) => {
    const res = await loginByMobile(params)
    setToken(res.data)
    token.value = res.data
    loginAfter()
  }

  const loginAfter = () => {
    router.push({ path: '/' })
  }

  const getUserInfo = async () => {
    const res = await getUserInfoApi()
    userInfo.realName = res.data.realName
    userInfo.avatar = res.data.avatar
  }

  const setTeam = (id: string) => {
    teamId.value = id
    setTeamId(id)
  }

  // 退出
  const logout = async () => {
    try {
      await logoutApi()

      resetToken()
      return true
    } catch (error) {
      return false
    }
  }
  return { name, avatar, login, logout, getUserInfo, resetToken, setTeam, teamId }
}

export const useUserStore = defineStore('user', storeSetup, {
  persist: { paths: ['token', 'teamId'], storage: localStorage }
})
